<template>
  <div class="add-role">
    <el-dialog :title="editTitleId===null?'新增职称':'修改职称'" :visible.sync="isVisible"
               :before-close="handleCloseDialog" width="45%">
      <el-card style="margin: 0 auto" shadow="never">
        <div class="add-role-input">
          <el-form label-width="100px" :model="addTitleMessage" ref="addTitleFrom" :rules="rules">
            <el-form-item label="职称名称：" prop="titleName">
              <el-input v-model="addTitleMessage.titleName" clearable></el-input>
            </el-form-item>
            <el-form-item label="职业分类：" prop="titleCategory">
              <el-input v-model="addTitleMessage.titleCategory" clearable></el-input>
            </el-form-item>
            <el-form-item label="职称级别：" prop="titleLevel">
              <el-select v-model="addTitleMessage.titleLevel" placeholder="请选择职称级别">
                <el-option v-for="item in typeOptions" :key="item.value" :value="item.value" :label="item.label">
                  {{ item.label }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <div class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddTitle(editTitleId==null?'add':'edit')">
          {{ editTitleId === null ? '确认添加' : '确认修改' }}
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import { mapState } from 'vuex'
import store from '@/store'
import {
  AddRoleApi,
  CheckAddRoleNameRepeatApi,
  CheckAddRoleRepeatApi,
  GetRoleByIdApi,
  UpdateRoleByIdApi
} from '@/request/role/role-api'
import { addTitleApi, GetTitleByIdApi, UpdateTitleByIdApi } from '@/request/title/title-api'

export default {
  data () {
    return {
      addTitleMessage: {},
      typeOptions: [
        {
          value: 1,
          label: '初级职称'
        },
        {
          value: 2,
          label: '中级职称'
        }, {
          value: 3,
          label: '高级职称'
        }
      ],
      rules: {
        titleName: {
          required: true,
          message: '职称名称必填!',
          trigger: 'blur'
        },
        titleCategory: {
          required: true,
          message: '职业类别必填！',
          trigger: 'blur'
        },
        titleLevel: {
          required: true,
          message: '职业级别必填！',
          trigger: 'blur'
        }
      },
    }
  },
  computed: {
    listenEditTitleId () {
      return store.state.TitleEditData.editTitleId
    },
    ...mapState({
      editTitleId: state => state.TitleEditData.editTitleId,
      isVisible: state => state.TitleEditData.isVisible,
    })
  },
  methods: {
    closeAddOrEdit () {
      this.addTitleMessage = {}
      store.commit('TitleEditData/changeIsVisible', false)
      store.commit('TitleEditData/changeEditTitleId', null)
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addTitleFrom'].clearValidate()
      })

    },
    async getTitleById (id) {
      let res = await GetTitleByIdApi(id)
      if (res&&res.code === 200) {
        this.addTitleMessage=res.data
      } else {
        this.$message.info('查询职称失败！')
      }
    },
    handleCloseDialog () {
      this.$confirm('确定取消操作吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(() => {
        this.closeAddOrEdit()
      }).catch((e) => {
        if (e === 'cancel') {
        }
      })
    },
    handleAddTitle (type) {
      //校验表单
      this.$refs.addTitleFrom.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          //是添加角色
          if (type === 'add') {
            this.$confirm('确定添加该职称信息吗？', '提示',
                {
                  'confirmButtonText': '确定',
                  'cancelButtonText': '取消',
                  'type': 'warning'
                }).then(async () => {
                  console.log(this.addTitleMessage)
              let res = await addTitleApi(this.addTitleMessage)
              if (res && res.code === 200) {
                this.$message.success('添加成功')
                this.$parent.init()
              } else {
                this.$message.success('添加失败')
              }
              this.closeAddOrEdit()
            }).catch((e) => {
              if (e === 'cancel') {
                this.$message.info('已取消添加角色')
              } else {
                this.$message.error('未知错误！')
              }
            })
          }
          else if (type === 'edit') {
            this.updateTitle()
          }
        }
      })
    },
    //修改角色
    updateTitle () {
      this.$confirm('确定修改该职称信息吗？', '提示',
          {
            'confirmButtonText': '确定',
            'cancelButtonText': '取消',
            'type': 'warning'
          }).then(async () => {
        let res = await UpdateTitleByIdApi(this.addTitleMessage)
        if (res.code === 200) {
          this.$notify.success({
            title: '修改成功',
            message: '修改职称信息成功'
          })
        } else {
          this.$message.error(res.msg)
        }
        this.closeAddOrEdit()
        this.$parent.init()
      }).catch((e) => {
        if (e === 'cancel') {
          this.$message.info('取消修改职称')
        }
      })
    },
  },
  watch: {
    listenEditTitleId: {
      immediate: true,
      handler (val, oldval) {
        if (val) {
          this.getTitleById(val)
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.add-role {
  .el-dialog {
    .el-card {
      width: 80%;

      .add-role-input {
        width: 80%;
        margin: 10px 20px;

        .el-input {
          width: 222px;
        }
      }
    }

    .dialog-footer {
      margin: 0 auto;
      padding: 20px 20px;
      max-width: 200px;
    }
  }
}

/deep/ .el-dialog {
  border-radius: 10px;
}
</style>
